<template>
  <div style="width: 100%; height: 100%">
    <guangbopanelCard :headerFlag="true">
      <template #header>
        <div style="display: flex; align-items: center; width: 100%">
          <div style="width: 15%; display: flex; align-items: center">
            <span class="searchColor themfontColor">文件名称</span>
            <el-input
              v-model="state.searchData.fileName"
              placeholder="请输入"
              style="width: 60%; margin-left: 15px"
              clearable
            ></el-input>
          </div>
          <div>
            <el-button type="primary" @click="queryFn">查询</el-button>
            <el-button @click="resetFn">重置</el-button>
          </div>
        </div>
      </template>
      <template #article>
        <guangbovxeTB
          ref="guangbovxeTB"
          title="音频管理"
          :tableheads_show="state.tableheads_show"
          :listUrl="state.listUrl"
          :caozuoList="state.caozuoList"
          @addFn="addFn"
          @delAllFn="delAllFn"
          @edit="editFn"
          @bofang="bofangFn"
          @shanchu="delFn"
        ></guangbovxeTB>
      </template>
    </guangbopanelCard>
    <!-- 新增 -->
    <el-dialog v-model="state.addFlag" width="30%" :before-close="handleClose">
      <template #title>
        <span class="themfontColor">{{ state.addTitle }}</span>
      </template>
      <div style="width: 100%; display: flex; justify-content: center">
        <el-form
          ref="formRef"
          :model="state.formData"
          :rules="state.formDataRules"
          label-width="120px"
        >
          <el-form-item label="名称" prop="fileName">
            <el-input
              v-model="state.formData.fileName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择文件">
            <el-upload
              ref="uploadRef"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :on-change="handleFileChange"
              class="upload-demo"
              accept=".swf, .flv, .mp3, .wav, .wma, .wmv, .mid, .avi, .mpg,.asf, .rm, .rmvb"
              :action="uploadFileUrl"
              :headers="headers"
              :auto-upload="true"
              drag
              :limit="1"
              :multiple="false"
              :file-list="state.fileList"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="upload__text">
                <div>点击或将文件拖拽到这里上传</div>
                <!-- <div>支持mp3格式，最大10MB</div> -->
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveAddFn"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 播放 -->
    <el-dialog
      v-model="state.bofangFlag"
      width="22%"
      :before-close="bofanghandleClose"
    >
      <template #title>
        <span class="themfontColor">播放</span>
      </template>
      <div style="text-align: center">
        <el-form
          ref="bofangRef"
          :model="state.form"
          :rules="state.rules"
          label-width="100px"
        >
          <el-form-item label="音乐名称：">
            <span class="themfontColor">{{
              state.detailData.originalName
            }}</span>
          </el-form-item>
          <el-form-item label="播放次数：" prop="num">
            <el-input
              v-model="state.form.num"
              type="Number"
              :min="1"
              :max="100"
              style="width: 240px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="广播号码：" prop="phone">
            <el-select v-model="state.form.phone" style="width: 240px" multiple>
              <el-option
                v-for="item in state.telephoneData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <!-- <audio src="@/assets/guangboimg/鸟叫.mp3" controls autoplay></audio> -->
        <!-- <el-button @click="startFn" type="primary">开启</el-button> -->
        <!-- <el-button @click="endFn">关闭</el-button> -->
        <!-- <audio :src="state.detailData.FilePath" controls autoplay></audio> -->
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="startFn" type="primary">开启</el-button>
          <!-- <el-button @click="endFn">关闭</el-button> -->
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, nextTick } from "vue-demi";
import axios from "@/utils/request";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { table_headers } from "@/assets/table_headers/table_headers";
import { getToken } from "@/utils/auth";
import usepagesStore from "@/store/modules/pages";
const userStore = usepagesStore();
const props = defineProps({});
const emit = defineEmits([""]);
const { proxy } = getCurrentInstance();
let uploadFileUrl = import.meta.env.VITE_APP_BASE_API + "/common/uploadUUID";
let headers = { Authorization: "Bearer " + getToken() };
let state = reactive({
  fileList: [],
  searchData: {},
  addTitle: "新增",
  luyouSelectData: [], //路由选择码
  luyouYuanSelectData: [], //路由选择源码
  formData: {},
  formDataRules: {
    fileName: [
      {
        required: true,
        message: "请输入名称",
        trigger: "blur",
      },
    ],
    type: [
      {
        required: true,
        message: "请输入业务类型",
        trigger: "blur",
      },
    ],
    routerChoice: [
      {
        required: true,
        message: "请输入路由选择码",
        trigger: "blur",
      },
    ],
    minLength: [
      {
        required: true,
        message: "请输入最小号长",
        trigger: "blur",
      },
    ],
    maxLength: [
      {
        required: true,
        message: "请输入最大号长",
        trigger: "blur",
      },
    ],
  },
  form: { num: 1, phone: [] },
  rules: {
    num: [
      {
        required: true,
        message: "请输入播放次数",
        trigger: "blur",
      },
    ],
    phone: [
      {
        required: true,
        message: "请选择广播号码",
        trigger: "change",
      },
    ],
  },
  addFlag: false,
  bofangFlag: false,
  caozuoList: [
    {
      caozuoType: "bofang",
      label: "播放",
      type: "text",
    },
    {
      caozuoType: "edit",
      label: "编辑",
      type: "text",
    },
    {
      caozuoType: "shanchu",
      label: "删除",
      type: "text",
    },
  ],
  selectData: [],
  tabledata: [],
  tableheads_show: computed(() => table_headers.t_sip_file),
  detailData: {},
  telephoneData: [],
  uploadData: {},
  uploadUrl: "",
  fileType: [
    "swf",
    "flv",
    "mp3",
    "wav",
    "wma",
    "wmv",
    "mid",
    "avi",
    "mpg",
    "asf",
    "rm",
    "rmvb",
  ],
  endData: "",
  listUrl: "/sip/config/file/list",
  addUrl: "/sip/config/file/add",
  editUrl: "/sip/config/file/edit",
  delUrl: "/sip/config/file/",
  detailUrl: "/sip/config/file/",
});
//新增弹层
const addFn = () => {
  //新增
  state.addTitle = "新增";
  state.addFlag = true;
};
const editFn = (row) => {
  //编辑
  console.log(row, "row");
  state.addTitle = "编辑";
  state.addFlag = true;
  state.formData = row;
  state.fileList = [{ name: row.originalName, url: row.url }];
  // state.formData.type = state.formData.type + "";
};
const handleClose = () => {
  //关闭
  state.addFlag = false;
  state.formData = {};
  state.fileList = [];
  proxy.$refs["formRef"].resetFields();
};
const saveAddFn = () => {
  //保存
  let url = state.addUrl;
  if (state.addTitle == "新增") {
    url = state.addUrl;
  } else {
    url = state.editUrl;
  }
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      axios
        .post(url, state.formData)
        .then((res) => {
          if (res.code == 200) {
            // state.addFlag = false;
            ElMessage.success(res.msg);
            proxy.$refs["guangbovxeTB"].getList();
            handleClose();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch((err) => {
          ElMessage.error(res.msg);
        });
    }
  });
};
const bofangFn = (row) => {
  //播放
  console.log(row, "row");
  state.detailData = row;
  state.bofangFlag = true;
};
const bofanghandleClose = (row) => {
  //播放关闭
  state.bofangFlag = false;
};
function startFn() {
  //开启
  proxy.$refs["bofangRef"].validate((isOk) => {
    if (isOk) {
      // const remainingPath = state.detailData.url.replace(
      //   /^https?:\/\/[^\/]+/,
      //   ""
      // );
      axios
        .post("/callingCenter/broadcast", {
          // type: state.detailData.type,
          guestNumbers: state.form.phone,
          fileUuid: [state.detailData.uuid],
          loopType: 0, //0次数,1时长
          loopCount: state.form.num,
        })
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success(res.msg);
            state.endData = res.data;
            state.bofangFlag = false; //返回data数据用以关闭
          } else {
            ElMessage.error(res.msg);
          }
        });
    }
  });
}
function endFn() {
  //关闭
  if (state.endData) {
    proxy.$refs["bofangRef"].validate((isOk) => {
      if (isOk) {
        axios
          .post(`/callingCenter/conference/close/${state.endData}`, {})
          .then((res) => {
            ElMessage.success("关闭成功");
            state.bofangFlag = false;
            // getList(0)
          });
      }
    });
  } else {
    ElMessage.error("请至首页广播中关闭!");
  }
}
const delAllFn = () => {
   if(userStore.records.length == 0){
    ElMessage.warning("请选择要删除的记录");
    return
  }else{
    let str=[]
    userStore.records.forEach(item => {
str.push(item.id)
    })
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios.delete(state.delUrl + str.join(",")).then((res) => {
        ElMessage.success("删除成功");
        userStore.records=[]
        proxy.$refs['guangbovxeTB'].getList()
      });
    })
    .catch(() => {});
  }
};
const delFn = (row) => {
  //删除
  state.detailData = row;
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios.delete(state.delUrl + row.id).then((res) => {
        ElMessage.success("删除成功");
        proxy.$refs["guangbovxeTB"].getList();
      });
    })
    .catch(() => {});
};
function handleFileChange(file) {}

function uploadSuccess(data) {
  console.log(data, "data");
  let val = data.newFileName.split(".")[0];
  state.formData.uuid = val;
  state.formData.originalName = data.originalFilename;
  state.formData.originalPath = data.fileName;
  state.formData.convertedPath = data.convertedPath;
  state.formData.fileSuffix = data.fileSuffix;
  state.formData.duration = data.duration;
  state.formData.url = data.url;
  state.formData.type = 0; //0=音乐库,1=录音,2=tts
}
async function beforeUpload(file) {
  console.log(file, "file");
  state.uploadData = file;
  if (file.type != "" || file.type != null || file.type != undefined) {
    //截取文件的后缀，判断文件类型
    const FileExt = file.name.replace(/.+\./, "").toLowerCase();
    file.name.substring(0, file.name.lastIndexOf(".")); //截取文件前缀
    //计算文件的大小
    const isLt5M = file.size / 1024 / 1024 < 10; //这里做文件大小限制
    //const isLt5M = file.size / 1024 < 500; //500kb
    //如果大于50M
    if (!isLt5M) {
      ElMessage.error("上传文件过大!");
      return false;
    } else {
      try {
        const compressedFile = await compressAudio(file);
        let pattern = /base64,(.*)/; // 使用正则表达式匹配指定字符后面的内容
        let result = compressedFile.match(pattern)[1]; // 提取匹配结果的第一个捕获组
        state.uploadUrl = result;
        // saveAddFn();
        // 这里可以将compressedFile发送到服务器
      } catch (error) {
        console.error("压缩失败:", error);
      }
    }

    //如果文件类型不在允许上传的范围内
    if (state.fileType.includes(FileExt)) {
      return true;
    } else {
      proxy.$message.error("请上传mp3格式文件!");
      return false;
    }
  }
}
function compressAudio(file) {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise((resolve, reject) => {
    reader.onload = (event) => {
      const compressedBase64 = event.target.result; // 获取Base64字符串
      // 这里可以添加压缩逻辑，例如使用lamejs或其他库压缩mp3
      // 压缩后的音频通常会更小，可以用来减少上传数据量
      // 压缩后的操作代码...
      resolve(compressedBase64);
    };
    reader.onerror = (error) => {
      reject(error);
    };
  });
}
const queryFn = () => {
  //查询
  let obj = {};
  obj.fileName = state.searchData.fileName;
  proxy.$refs["guangbovxeTB"].state.searchData = obj;
  proxy.$refs["guangbovxeTB"].getList();
};
const resetFn = () => {
  //重置
  state.searchData = {};
  proxy.$refs["guangbovxeTB"].state.searchData = {};
  proxy.$refs["guangbovxeTB"].getList();
};
function getSelect() {
  axios.post("/sip/config/user/listNoPage", {}).then((res) => {
    state.telephoneData = res.data.map((item) => {
      return {
        value: item.userNumber,
        label: item.userNumber,
      };
    });
  });
}
onMounted(() => {
  getSelect();
  queryFn();
});
</script>